import RequestSuccessCallbackResult = WechatMiniprogram.RequestSuccessCallbackResult
import ReadFileSuccessCallbackResult = WechatMiniprogram.ReadFileSuccessCallbackResult
import ComponentInstance = WechatMiniprogram.Component.TrivialInstance
import Canvas = WechatMiniprogram.Canvas
import CanvasContext = WechatMiniprogram.CanvasContext
import { platformBridge } from '../Platform'

const wx = platformBridge()

export function isUrl(url: string): boolean {
  const regUrl = /^((https|http|ftp|rtsp|mms):\/\/)(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z].[a-zA-Z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+\/?)$/
  return regUrl.test(url)
}

export function getFileByRequest(url: string): Promise<RequestSuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      responseType: 'arraybuffer',
      success: resolve,
      fail: reject
    })
  })
}

export function getFileByManager(url: string): Promise<ReadFileSuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().readFile({
      filePath: url,
      success: resolve,
      fail: reject
    })
  })
}

export function getCanvas(selector: string, component?: ComponentInstance): Promise<{ canvas: Canvas, ctx: CanvasContext, dpr: number }> {
  return new Promise((resolve, reject) => {
    let query = wx.createSelectorQuery()
    if (component) query = query.in(component)
    
    query.select(selector).fields({ node: true, size: true }).exec((result: any) => {
      const canvas: Canvas = result?.[0].node
      if (!canvas) return reject('canvas not found.')
      
      const ctx: CanvasContext = canvas.getContext('2d')
      if (!ctx) return reject('canvas context not found.')
      
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width = result[0].width * dpr
      canvas.height = result[0].height * dpr
      resolve({ canvas, ctx, dpr })
    })
  })
}
